package com.example.fengyungo.controller.user.driver;

import com.example.fengyungo.constant.MsgConstant;
import com.example.fengyungo.constant.OrderConstant;
import com.example.fengyungo.domain.entity.Order;
import com.example.fengyungo.domain.pojo.Driver;
import com.example.fengyungo.domain.pojo.User;
import com.example.fengyungo.domain.vo.OrderDetailsVO;
import com.example.fengyungo.result.Result;
import com.example.fengyungo.service.DriverService;
import com.example.fengyungo.service.OrderService;
import com.example.fengyungo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user/driver")
public class DriverOrderController {

    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 清理缓存数据
     *
     * @param pattern String
     */
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 查询可接订单
     *
     * @return Result<List < Order>>
     */
    @GetMapping("/access")
    @Cacheable(value = "ordergetAccessOrder")
    public Result<List<OrderDetailsVO>> getAccessOrder() {
        return orderService.getAccessOrder();
    }

    /**
     * 根据司机id查询订单（司机已接订单）
     *
     * @param receiverId 司机id
     * @return Result<List < Order>>
     */
    @GetMapping("/{receiverId}")
    @Cacheable(value = "order", key = "'getOrdersByDriver'+#receiverId")
    public Result<List<OrderDetailsVO>> getOrdersByDriver(@PathVariable String receiverId) {
        // TODO: 2024/2/9 优化sql
        return orderService.getOrdersByDriver(receiverId);
    }

    /**
     * 根据起点或终点查询司机可接的订单
     *
     * @param order Order（包括起点终点）
     * @return List<Order>
     */
    @PostMapping("/beginOrEnd")
    public Result<List<OrderDetailsVO>> getOrdersByPosition(@RequestBody Order order) {
        String begin = order.getBegin();
        String end = order.getEnd();
        List<OrderDetailsVO> ordersByPosition = orderService.getOrdersByPosition(begin, end);
        return Result.success(ordersByPosition);
    }

    /**
     * 司机接受订单
     *
     * @param receiverId 接受者id，司机id
     * @param number     订单编号
     * @return Result
     */
    @PutMapping("/{receiverId}/{number}")
    public Result<Boolean> receiveOrder(@PathVariable String receiverId, @PathVariable String number) {
        // 检查司机状态是否具备接单权限
        Boolean judgeStatus = driverService.judgeStatus(receiverId);
        if (!judgeStatus) {
            return Result.error(MsgConstant.NOT_DRIVER);
        }
        // 接受订单
        Boolean res = orderService.updateReceiverIdAndOrderStatusByNumber(receiverId, number);
        // 清除缓存
        cleanCache("fengyungoorder*");
        if (res) {
            return Result.success();
        } else {
            return Result.error("");
        }
    }

    /**
     * 修改货物状态为已送达
     *
     * @param number String，订单编号
     * @return Result
     */
    @PutMapping("/arrived/{number}")
    public Result<Boolean> arrived(@PathVariable String number) {
        Order order = new Order();
        order.setNumber(number);
        order.setOrderStatus(OrderConstant.HAS_ARRIVED);
        Integer res = orderService.updateOrderByNumber(order);
        if (res > 0) {
            // 清除缓存
            cleanCache("fengyungoorder*");
            return Result.success();
        } else {
            return Result.error(MsgConstant.ORDER_STATUS_UPDATE_FAIL);
        }
    }
}
